<template>
    <el-dialog v-model="showDialog" title="配置角色菜单" @close="close" style="width: 30%">
        <el-tree
                ref="treeRef"
                :data="treeData"
                show-checkbox
                default-expand-all
                node-key="id"
                highlight-current
                :props="defaultProps"
        />
        <div class="buttons" style="display: flex;align-items:center;justify-content:center;">
            <el-button type="primary" plain  activity @click="saveMenusForRole">保存</el-button>
            <el-button type="primary" plain  activity @click="close">取消</el-button>
        </div>
    </el-dialog>
</template>

<script setup>
    import {ref,reactive,nextTick,onUpdated,onMounted} from 'vue'
    import request from '@/utils/request.js'
    import { ElMessage } from 'element-plus'
    const  emits = defineEmits(['reload'])
    const  treeRef = ref(null)
    let  showDialog = ref(false)
    let props = defineProps(['id'])

    const defaultProps = {
        children: 'children',
        label: 'name',
    }
    let treeData = reactive([])


    onMounted(function () {
        request.get(`/api/menu/getMenus`).then(resp => {
            treeData.push(...resp)
            treeData.value = resp
        })
    })

    onUpdated(function () {
        if(showDialog.value == true){
        request.get(`/api/menu/getMenusForRole/${props.id}`).then(resp => {
            treeRef.value.setCheckedKeys(resp,false)
            })
        }
    })

    function show(){
        showDialog.value = true
    }
    function close(){
        showDialog.value = false
    }

    function saveMenusForRole(){
        //获取所有被勾选和半勾选的节点
        let nodes = treeRef.value.getCheckedNodes(false,true)
        let checkdIds = nodes.map( e => e.id)
        let menusForRole = {roleId:props.id, menuIds:checkdIds}
        request.post("/api/menu/saveMenusForRole", menusForRole).then(resp => {
            success()
        })
    }

    function success(){
        ElMessage({message: '修改成功！',type: 'success'})
        close()
        emits("reload")
    }
    defineExpose({show})
</script>

<style scoped>

</style>